from flask import jsonify, request
from flask_login import login_required
import json
from tencentcloud.vod.v20180717 import vod_client, models
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from api.db.services.DOV_service import DocumentService



# 初始化腾讯云的凭证``
cred = credential.Credential("AKIDwbAh3B8tX1KVUGpGxmUK0e9UcXIpDZlo", "vgFfuzuc6NTP9lBOOBk6IKBqJZklaCcx")

# 配置 HTTP 配置
http_profile = HttpProfile()
http_profile.endpoint = "vod.tencentcloudapi.com"

# 创建 ClientProfile 并将 HTTP 配置关联到它
client_profile = ClientProfile()
client_profile.httpProfile = http_profile

# 创建 VodClient 客户端
client = vod_client.VodClient(cred, "ap-guangzhou", client_profile)

@manager.route('/getVideo', methods=['GET'])
def get_video_list():
    # 获取前端请求的分页参数，默认第一页，最多100个视频
    limit = int(request.args.get('limit', 100))  # 每次请求获取100个视频
    offset = int(request.args.get('offset', 0))  # 从第0个视频开始

    # 获取 FileIds 参数（以逗号分隔的字符串）
    file_ids = request.args.get('file_ids')
    file_ids_list = file_ids.split(',') if file_ids else []

    if not file_ids_list:
        return get_data_error_result(message="No video ID provided")

    # 配置请求参数
    params = {
        "Limit": limit,  # 返回的最大视频数量
        "Offset": offset,  # 偏移量，用于分页
        "FileIds": file_ids_list,
    }

    # 创建请求对象
    request_obj = models.DescribeMediaInfosRequest()
    request_obj.from_json_string(json.dumps(params))

    try:
        # 调用 API 获取视频信息
        response = client.DescribeMediaInfos(request_obj)
        # 如果api没有找到正确信息，不报错，直接返回没有找到信息的提示
        if not response.MediaInfoSet:
            return get_data_error_result(message="No video information found")
        #正确处理API返回结构
        video_detail = {
            "MediaInfoSet": [json.loads(video.to_json_string()) for video in response.MediaInfoSet],
            "NotExistFileIdSet": response.NotExistFileIdSet,
            "RequestId": response.RequestId
        }
        
        video_detail_mes=video_detail["MediaInfoSet"]
        result={
            "Name":video_detail_mes[0]['BasicInfo']['Name'],
            "CoverUrl":video_detail_mes[0]['BasicInfo']['CoverUrl'],
            "VideoUrl":video_detail_mes[0]['BasicInfo']['MediaUrl'],
            "CreateTime":video_detail_mes[0]['BasicInfo']['CreateTime'],
            "Duration":video_detail_mes[0]['MetaData']['Duration'],
            "ID":video_detail_mes[0]['BasicInfo']['Vid']
        }
        # 返回所有视频的信息
        return get_json_result(data=result)

    except Exception as e:
        return jsonify({"error": str(e)}), 500
    
    
@manager.route('/get_videos', methods=['GET'])
def get_videos():
    try:
        # 获取前端请求的分页参数，默认第一页，最多100个视频
        limit = int(request.args.get('limit', 20))  # 每次请求获取20个视频
        offset = int(request.args.get('offset', 0))  # 从第0个视频开始

        # 初始化请求对象
        search_req = models.SearchMediaRequest()

        # 设置分页参数
        search_req.Offset = offset
        search_req.Limit = limit

        # 调用接口搜索视频信息
        search_resp = client.SearchMedia(search_req)

        # 如果没有找到视频列表，就返回空列表
        if not search_resp.MediaInfoSet:
            return get_data_error_result(message="No video list information found")
        result={
            "TotalCount": search_resp.TotalCount,
            "MediaInfoSet": [
                json.loads(video.to_json_string()) 
                for video in search_resp.MediaInfoSet
            ],
            "RequestId": search_resp.RequestId
        }
        return get_json_result(data=result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def get_video_info(file_ids, limit=100, offset=0):
    # 统一处理file_ids参数类型
    if isinstance(file_ids, str):
        file_ids_list = file_ids.split(',')
    elif isinstance(file_ids, list):
        file_ids_list = file_ids
    else:
        return None, "Invalid file_ids type"

    if not file_ids_list:
        return None, "Missing required parameter: file_ids"

    # 配置请求参数
    params = {
        "Limit": limit,
        "Offset": offset,
        "FileIds": file_ids_list,
    }

    # 创建请求对象
    request_obj = models.DescribeMediaInfosRequest()
    request_obj.from_json_string(json.dumps(params))

    try:
        # 调用API获取视频信息
        response = client.DescribeMediaInfos(request_obj)
        # 如果没有找到视频信息，就返回0
        if not response.MediaInfoSet:
            return 0
        # 处理API返回结构
        video_detail = {
            "MediaInfoSet": [json.loads(video.to_json_string()) for video in response.MediaInfoSet],
            "NotExistFileIdSet": response.NotExistFileIdSet,
            "RequestId": response.RequestId
        }

        video_detail_mes = video_detail["MediaInfoSet"]
        result = {
            "Name": video_detail_mes[0]['BasicInfo']['Name'],
            "CoverUrl": video_detail_mes[0]['BasicInfo']['CoverUrl'],
            "VideoUrl": video_detail_mes[0]['BasicInfo']['MediaUrl'],
            "CreateTime": video_detail_mes[0]['BasicInfo']['CreateTime'],
            "Duration": video_detail_mes[0]['MetaData']['Duration'],
            "ID": video_detail_mes[0]['BasicInfo']['Vid']
        }
        return result

    except Exception as e:
        return 0

# 根据文档id获得文档url
@manager.route('/document_oss_get', methods=['GET'])
def document_oss_get():
    try:
        # 获取前端请求的文档id
        document_id = request.args.get('document_id')
        if not document_id:
            return get_data_error_result(message="文档ID不能为空")
            
        # 从数据库获取文档信息
        document = DocumentService.get_document_by_id(document_id)
        if not document:
            return get_data_error_result(message="文档不存在")
            
        # 获取OSS URL
        oss_url = document.oss_url
        if not oss_url:
            return get_data_error_result(message="文档未绑定OSS资源")
            
        result = {"oss_url": oss_url}
        return get_json_result(data=result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 根据文档id获得视频url
@manager.route('/document_video_get', methods=['GET'])
def document_video_get():
    try:
        # 获取前端请求的文档id
        document_id = request.args.get('document_id')
        if not document_id:
            return get_data_error_result(message="文档ID不能为空")
            
        # 从数据库获取文档信息
        document = DocumentService.get_document_by_id(document_id)
        if not document:
            return get_data_error_result(message="文档不存在")
            
        # 获取视频ID
        video_id = document.video_id
        if not video_id:
            return get_data_error_result(message="文档未绑定视频资源")
            
        # 调用视频id获取视频详细信息的接口
        video_detail = get_video_info(video_id)
        if video_detail == 0:
            return get_data_error_result(message="未找到视频信息")
            
        return get_json_result(data=video_detail)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    
    
# 获取用户的知识库列表（通过邮箱）
@manager.route('/get_knowledgebase_name', methods=['POST'])
@login_required
def get_knowledgebase_name():
    try:
        data = request.get_json()
        email = data.get('email')
        
        if not email:
            return get_data_error_result(message="Email is required")
            
        # 调用服务获取数据
        result = DocumentService.get_knowledgebases_by_email(email)
        return get_json_result(data=result)
        
    except ValueError as e:
        return get_data_error_result(message=str(e))
    except Exception as e:
        return get_data_error_result(message=str(e))
    
    
@manager.route('/documents', methods=['POST'])
@login_required
def get_documents():
    try:
        data = request.get_json()
        
        # 获取查询参数
        kb_id = data.get('kb_id')  # 知识库ID【
        name = data.get('name')    # 文档名称
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        order_by = data.get('order_by', 'date')  # 默认按日期排序
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        
        # 调用服务获取数据
        result = DocumentService.get_documents(
            kb_id=kb_id,
            name=name,
            start_date=start_date,
            end_date=end_date,
            order_by=order_by,
            page=page,
            page_size=page_size
        )

        return get_json_result(data=result)
    except Exception as e:
        return get_data_error_result(message=str(e))

@manager.route('/documents/resources', methods=['POST'])
@login_required
def update_document_resources():
    try:
        data = request.json
        document_id = data.get('document_id')
        oss_url = data.get('oss_url', None)  
        video_id = data.get('video_id', None)  

        if not document_id:
            return get_data_error_result(message="文档ID不能为空",code=400)
            
        # 检查文档是否存在
        document = DocumentService.get_document_by_id(document_id)
        if not document:
            return get_data_error_result(message="文档不存在",code=400)
            
        # 更新资源
        updated = DocumentService.update_document_resources(
            document_id=document_id,
            oss_url=oss_url,
            video_id=video_id
        )
        
        if not updated:
            return get_data_error_result(message="更新失败")
            
        return get_json_result(data=True)
    except Exception as e:
        return get_data_error_result(message=str(e))


def get_json_result(code=0, message="success", data=None):
    response = {"code": code, "message": message, "data": data}
    return jsonify(response)

def get_data_error_result(code=0, message=None):
    response = {"code": code, "message": message}
    return jsonify(response)
